<template>
  <div style="width:100%;height:100%;position: relative" ref="mapBox">
    <!--    操作菜单 B-->
    <div class='control'>
      <div class='l_1' @click='openbm(0)' title="底图">
        <img src="../../static/images/icon/l1.png" alt="">
      </div>
      <!-- <div class='l_1' @click='openbm(1)' title="面">
        <img src="../../static/images/icon/l2.png" alt="">
      </div>
      <div class='l_1' @click='openbm(2)' title="点">
        <img src="../../static/images/icon/l3.png" alt="">
      </div>
      <div class='l_1' @click='openbm(3)' title="线">
        <img src="../../static/images/icon/l4.png" alt="">
      </div> -->



      <!-- <div class="l_1" @click="openbm(1)" title="动物"> -->
      <div class="l_1"  title="动物">
        <img src="../../static/images/icon/dongwu.png" alt="" style="width: .3rem;height: .3rem;" />
      </div>
      <!-- <div class="l_1" @click="openbm(2)" title="植物"> -->
      <div class="l_1" title="植物">
        <img src="../../static/images/icon/zhiwu.png" alt="" style="width: .3rem;height: .3rem;" />
      </div>
      <!-- <div class="l_1" @click="openbm(3)" title="设备设施"> -->
      <div class="l_1"  title="设备设施">
        <img src="../../static/images/icon/shebeisheshi.png" alt="" style="width: .3rem;height: .3rem;" />
      </div>
      <!-- <div class="l_1" @click="openbm(5)" title="其他"> -->
      <div class="l_1" title="其他">
        <img src="../../static/images/icon/qita.png" alt="" style="width: .3rem;height: .3rem;" />
      </div>
      <div class='l_1' @click='openbm(6)' title="业务系统发布图层">
        <img src="../../static/images/icon/kjlb.png" alt="" style="width: .3rem;height: .3rem;">
      </div>
      <div class='l_1' @click='openbm(4)' title="标注">
        <img src="../../static/images/icon/l5.png" alt="">
      </div>

      <!--      <div class='l_1'>-->
      <!--        <img src="../../static/images/icon/l6.png" alt="">-->
      <!--      </div>-->
      <div class='l_1' @click='switch3d' title="二三维转换">
        <img :src="is3d ? '../../static/images/icon/l8.png' : '../../static/images/icon/l7.png'" alt="">
      </div>
      <div class='b1' title="地图测量">
        <img :src="b1f" alt="">
        <div class="t_1" @click='cd(1, "LineString")'></div>
        <div class="t_2" @click='cd(2, "Polygon")'></div>
        <div class="t_3" @click='cd(3, "del")'></div>
      </div>
    </div>
    <!--    操作菜单 E-->
    <!--    展开图层 B-->
    <div class='z_1' v-show='showList[0].boo'>
      <div class='lx'>
      </div>
      <div class='fx'>
        <el-radio-group v-model="bml" v-for='(bm, index) in bmList' :key='index' @change='switchBmap(bm)'
          style='margin-bottom: .2rem;'>
          <el-radio :label="bm.name">{{ bm.name }}</el-radio>
        </el-radio-group>
      </div>
    </div>

    <div class='z_2' v-show='showList[1].boo'>
      <div class='lx'>
      </div>
      <div class='fx'>
        <el-checkbox-group v-model="blarr">
          <el-checkbox v-for='bl in blList' @change='dlayer(blarr, bl)' :key='bl.name' :label="bl.name"
            style='margin-bottom: .2rem;'>
          </el-checkbox>
        </el-checkbox-group>
      </div>
    </div>

    <div class='z_3' v-show='showList[2].boo'>
      <div class='lx'>
      </div>
      <div class='fx'>
        <el-checkbox-group v-model="bparr">
          <el-checkbox v-for='bl in bpList' :key='bl.name' :label="bl.name" @change='dlayer(bparr, bl)'
            style='margin-bottom: .2rem;'>
          </el-checkbox>
        </el-checkbox-group>
      </div>
    </div>

    <div class='z_4' v-show='showList[3].boo'>
      <div class='lx'>
      </div>
      <div class='fx'>
        <el-checkbox-group v-model="bliarr">
          <el-checkbox v-for='(bl, index) in bliList' :key='bl.name' :label="bl.name" @change='dlayer(bliarr, bl)'
            style='margin-bottom: .2rem;'>
          </el-checkbox>
        </el-checkbox-group>
      </div>
    </div>

    <div class='z_7' v-show='showList[6].boo'>
      <div class='lx'>
      </div>
      <div class='fx'>
        <el-checkbox-group v-model="lbarr">
          <el-checkbox v-for='(bl, index) in kljbarr' :key='bl.id' :label="bl.id" @change='lbdlayer(lbarr, bl)'
            style='margin-bottom: .2rem;'>
            {{ bl.name }}
          </el-checkbox>
        </el-checkbox-group>
      </div>
    </div>

    <div class="z_6" v-show="showList[5].boo">
      <div class="lx"></div>
      <div class="newfx">
        <el-checkbox-group v-model="otherarr">
          <el-checkbox v-for="bl in otherList" :key="bl.name" :label="bl.name" @change="dlayer(otherarr, bl)"
            style="margin-bottom: .2rem;">
          </el-checkbox>
        </el-checkbox-group>
      </div>
    </div>

    <div class='z_5' v-show='showList[4].boo'>
      <div class='lx'>
      </div>
      <div class='fx' style='padding: .1rem;width: 5.8rem;text-align: left'>
        &nbsp;
        <span>经度：</span>
        <el-input style='width: 1.2rem;display: inline-block' placeholder="例：116.46" v-model="lon"
          onkeyup="value=value.replace(/^\D*(\d*(?:\.\d{0,4})?).*$/g, '$1')"></el-input>
        &nbsp;
        &nbsp;
        <span>纬度：</span>
        <el-input style='width: 1.2rem;display: inline-block' placeholder="例：49.46" v-model="lat"
          onkeyup="value=value.replace(/^\D*(\d*(?:\.\d{0,4})?).*$/g, '$1')"></el-input>
        &nbsp;
        &nbsp;
        <el-button @click='setLocation(lon, lat)' style='background-color: #00c853;color: #FFFFFF'>标注
        </el-button>
        <el-button @click='delLocation' style='background-color: #00c853;color: #FFFFFF'>清除
        </el-button>
      </div>
    </div>


    <!--    展开图层 E-->
    <!--    显示经纬度容器 B-->
    <div id="mouse-position"></div>
    <!--    显示经纬度容器 E-->
    <!--    地图弹窗B-->
    <div style='display: none'>
      <div id="popup" class="ol-popup">
        <a href="#" id="popup-closer" class="ol-popup-closer" @click="closer"></a>
        <div id="popup-content" ref="content">
          <div class="mapImgBox" @click="fimg(pop_P)">
            <img v-show="isMp4(iscloud(pop_P)) == '照片'" :src="iscloud(pop_P)" alt="">
            <video v-show="isMp4(iscloud(pop_P)) == '视频'" controls loop="loop" :src="iscloud(pop_P)"></video>
          </div>
          <div class="isshowdetails" v-show="isdetails">
            <div class="isshowdetailsbtn" @click="mapgodetails(isdetailsLink)">
              <span>{{ isdetailsTetx }}</span>
            </div>
            <div class="isshowdetailsbtn" v-if="jingDing != undefined && jingDing.imageStatus == 0"
              style="margin-left: .2rem;" @click="dzJd">
              <span>鉴定</span>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!--    地图弹窗E-->


    <div id="popup" class="ol-popup" style="display: none;">
      <a href="#" id="newpopup-closer" class="ol-popup-closer"></a>
      <div id="newpopup-content" class="content-box">
      </div>
    </div>

  </div>
</template>

<script>
//  import MapPointData from "./Mapdata.vue";
import olMap from "ol/Map";
import View from "ol/View";
import VectorSources from 'ol/source/Vector';
import { Vector as VectorSource, XYZ } from "ol/source";
import * as olProj from "ol/proj";
import { Heatmap as HeatmapLayer, Image as ImageLayer, Tile as TileLayer, Vector as VectorLayer } from "ol/layer";
import ImageWMS from 'ol/source/ImageWMS';
import WMTS from 'ol/source/WMTS';
import WMTSTileGrid from 'ol/tilegrid/WMTS';
import { Circle as CircleStyle, Fill, Icon, Stroke, Style, Text } from 'ol/style';
import GeoJSON from "ol/format/GeoJSON";
import MousePosition from 'ol/control/MousePosition';
import { createStringXY } from 'ol/coordinate';
import { getArea, getLength } from 'ol/sphere';
import { DragBox, Draw, Modify, Select } from 'ol/interaction';
import { LineString, Polygon } from 'ol/geom';
import Overlay from 'ol/Overlay';
import { unByKey } from 'ol/Observable';
import { getTopLeft, getWidth, extend, getCenter } from 'ol/extent.js';
import { platformModifierKeyOnly } from 'ol/events/condition';
import { defaults as defaultControls, OverviewMap } from 'ol/control';
//  网页菜单 B
import 'ol-contextmenu/dist/ol-contextmenu.min.css';
//  import Cmenu from 'ol-contextmenu/dist/ol-contextmenu'
//  网页菜单 E
//cesium B
import "ol/ol.css";
import Cesium from "cesium/Cesium";
import OLCesium from "olcs/OLCesium.js";
//接入服务 B
import http from '../utils/http'
import api from '../utils/api'

window["Cesium"] = Cesium;
//cesium E
//接入服务 E
export default {
  name: 'children',
  data() {
    return {
      //        Mapdata: MapPointData.MapPoint,
      Map: null,
      ol3d: {},
      bml: "离线",
      showList: [
        { boo: false },
        { boo: false },
        { boo: false },
        { boo: false },
        { boo: false },
        { boo: false },
        { boo: false },
        { boo: false },
        { boo: false },
      ],
      bmList: [],
      blList: [],
      bpList: [],
      bliList: [],
      otherList: [],
      otherarr: [],
      blarr: [],
      bparr: [],
      bliarr: [],
      kljbarr: [],
      lbarr: [],
      lon: "",
      lat: "",
      is3d: false,
      b1f: '../../static/images/icon/b1.png',
      center: [],
      level: 8,
      totalMap: {},
      levelNumber: 9,
      vectorSource: null,//图层源
      drawMesasure: null,
      pop_List: [],
      pop_P: [],
      bsl: [],
      rightMenu: null,
      isshowP: true,
      areaId: "",
      //详情按钮文字显示 文字 链接
      isdetails: false,
      isdetailsTetx: "",
      opennew: false,
      isdetailsLink: {},
      dwindex: 1,
      jingDing: {},
      // 勘界立标
      kjlbArr: []
    };
  },
  watch: {},
  created() {
    this.areaId = sessionStorage.getItem('areaId');
    this.$axios.get('/api/area' + "/" + this.areaId)
      .then(res => {
        this.center = [res.data.mapConfig.lon, res.data.mapConfig.lat];
        this.level = res.data.mapConfig.level;
      })
      .catch(err => {

      })
  },
  mounted() {
    //监测页面变化
    var elementResizeDetectorMaker = require("element-resize-detector");//导入
    // 创建实例
    var erd = elementResizeDetectorMaker();
    // 创建实例带参
    var erdUltraFast = elementResizeDetectorMaker({
      strategy: "scroll", //<- For ultra performance.
      callOnAdd: true,
      debug: true
    }), vm = this;
    //监听id为test的元素 大小变化
    erd.listenTo(this.$el, function (element) {
      if (vm.Map != null) {
        vm.Map.updateSize();
      }
    });
    //监测页面变化

  },
  methods: {
    //创建地图and cesium
    creationMap() {
      var container = document.getElementById('popup');
      this.puplay = new Overlay({
        element: container,
        autoPan: true,
        autoPanAnimation: {
          duration: 250
        }
      });
      let mz = 0, xz = 0;
      // this.bmList.forEach(e => {
      //   if (e.isShow) {
      //     mz = e.minZoom;
      //     xz = e.maxZoom;
      //   }
      // });
      // var maxExtent = boundingExtent([[63.66, 3.86], [185.05, 68.55]]);
      this.Map = new olMap({
        target: this.$el,
        layers: [],
        overlays: [this.puplay],
        // overlays: [this.overlay],
        controls: defaultControls({
          attribution: false,
          zoom: false,
          rotate: false
        }).extend([new OverviewMap()]),
        view: new View({
          //设置中心点
          center: olProj.fromLonLat(this.center),
          zoom: this.level,
          // minZoom: 10,
          // maxZoom: 18,
          // extent: olProj.transformExtent(maxExtent, 'EPSG:4326', 'EPSG:3857')
        })
      });
      //创建图层对象
      this.totalMap["bsaeMap"] = new TileLayer({
        source: new XYZ({
          url: 'http://t3.tianditu.com/DataServer?T=img_w&x={x}&y={y}&l={z}&tk=f24cec70606332017dcd39a4fb60dd11'   //正常的
          // url: 'http://172.16.76.10:1087/api/sync/mapImg.do?id=houhe-img-0000018&x={x}&y={y}&z={z}'  //后河离线版
        })
      })
      this.Map.addLayer(this.totalMap["bsaeMap"]);
      //移入鼠标显示经纬度
      var mousePositionControl = new MousePosition({
        coordinateFormat: createStringXY(4),
        projection: 'EPSG:4326',
        // comment the following two lines to have the mouse position
        // be placed within the map.
        className: 'custom-mouse-position',
        target: document.getElementById('mouse-position'),
        undefinedHTML: '&nbsp;'
      });
      this.Map.addControl(mousePositionControl);
      var _self = this;
      this.Map.on('singleclick', function (event) {
        var feature = _self.Map.forEachFeatureAtPixel(event.pixel,
          function (feature, layer) {
            return feature;
          });
        let lonlat = olProj.transform(event.coordinate, 'EPSG:3857', 'EPSG:4326');
        _self.$emit('SonData', lonlat);
        var coordinate = event.coordinate;
        if (typeof (feature) != "undefined") {
          if (feature.get("data") != undefined) {
            var x = [], y = [];
            if (feature.get("data").hasOwnProperty('mtl')) {
              x = feature.get("data").mtl;
              y = feature.get("data").mediaList;
              _self.pop_List = x.concat([]);
              _self.pop_P = y.concat([]);
              _self.jingDing = feature.get("data").obj;
              _self.isdetails = feature.get("data").isdetails;
              _self.isdetailsTetx = feature.get("data").isdetailsTetx;
              _self.opennew = feature.get("data").opennew;
              _self.isdetailsLink = Object.assign({}, feature.get("data").isdetailsLink);
              _self.puplay.setPosition(coordinate);
            }
            if (feature.get("data").hasOwnProperty('showpic')) {
              _self.isshowP = false
            }
          }
        }
      });
      this.getNewlayer()
      this.getkjlblayer()
      // (async function () {
      //   let res = await http.get(api.getLayers, {
      //     areaId: _self.areaId
      //   })
      //   if (res.data.status == 'success') {
      //     _self.bmList = res.data.data.base;
      //     _self.blList = res.data.data.polygon;
      //     _self.bpList = res.data.data.point;
      //     _self.bliList = res.data.data.line;
      //     setTimeout(function () {
      //       _self.blList.forEach(e => {
      //         if (e.isShow) {
      //           _self.dlayer([e.name], e)
      //           _self.blarr.push(e.name)
      //         }
      //       })
      //     }, 300)
      //   } else {
      //     alert('服务器异常，联系后台管理员！')
      //   }
      // })()
    },
    async getNewlayer() {
      var vm = this;
      let res = await http.get(api.Newlayer, {
        areaId: this.areaId
      });
      console.log(res, '图层');

      if (res.data.status == "success") {
        vm.bmList = res.data.data.base;
        vm.blList = res.data.data.animal;
        vm.bpList = res.data.data.plant;
        vm.bliList = res.data.data.device;
        vm.otherList = res.data.data.other;
        // setTimeout(function () {
        //   vm.otherList.forEach(e => {
        //     if (e.isShow) {
        //       vm.dlayer([e.name], e);
        //       vm.otherarr.push(e.name);
        //     }
        //   });
        // }, 300);
        setTimeout(function () {
          vm.bliList.forEach(e => {
            if (e.isShow) {
              vm.dlayer([e.name], e);
              vm.bliarr.push(e.name);
              // vm.blarr.push(e.name)
            }
          });
        }, 300);
      } else {
        alert("服务器异常，联系后台管理员！");
      }
    },

    async getkjlblayer() {
      let res = await http.get(api.NewlayerAdd, {
        areaId: this.areaId
      })
      console.log(res, 'ressss');
      if (res.data.code == 200) {
        this.kljbarr = res.data.data
      }
    },

    dzJd() {
      this.$emit('dzjd', this.jingDing)
    },
    addGif() {
      let _that = this;
      let mapDom = this.$refs.mapBox;
      let markerPoint = null;
      let coordinates = [[115.824332, 40.521668], [115.87557800, 40.55880500]];
      for (let i = 0; i < coordinates.length; i++) {
        var oDiv = document.createElement("span");
        oDiv.id = "gif-" + i;
        mapDom.appendChild(oDiv);
        this.$nextTick(() => {
          markerPoint = new Overlay({
            position: olProj.fromLonLat([
              coordinates[i][0],
              coordinates[i][1]
            ]),
            positioning: "center-center",
            element: document.getElementById("gif-" + i),
            stopEvent: false
          });
          this.Map.addOverlay(markerPoint);
        });
      }
    },
    //编辑图层
    setLayerModify(uniqueId) {
      var modify = new Modify({ source: this.totalMap[uniqueId].getSource() });
      let arr = this.Map.getInteractions();
      let vm = this;
      arr.forEach(e => {
        if (e instanceof Modify) {
          this.Map.removeInteraction(e);
        }
      })
      this.Map.addInteraction(modify);
    },
    //将图层生成geojson数据
    saveLayerToGeojson(uniqueId) {
      let featureArr = this.totalMap[uniqueId].getSource().getFeatures();
      let geojson = (new GeoJSON({
        defaultDataProjection: 'EPSG:4326',
        featureProjection: 'EPSG:3857'
      })).writeFeatures(featureArr);
      return geojson;
    },
    //手动定位
    artificialLocation(data, lc) {
      var coordinate = olProj.fromLonLat(lc);
      var closer = document.getElementById('popup-closer');
      this.puplay.setPosition(undefined);
      closer.blur();
      let x = [], y = [];
      x = data.mtl;
      y = data.mediaList;
      this.pop_List = x.concat([]);
      this.pop_P = y.concat([]);
      this.jingDing = data.obj;
      this.isdetails = data.isdetails;
      this.isdetailsTetx = data.isdetailsTetx;
      this.isdetailsLink = data.isdetailsLink;
      this.opennew = data.opennew;
      if (data.hasOwnProperty('showpic')) {
        this.isshowP = false
      }
      this.puplay.setPosition(coordinate);
      // this.Map.getView().setCenter(coordinate);
    },
    drawHeatMap(uniqueId, fenbu) {
      //判断是否已经存在相同id的图层 如果有删掉，再重新绘制
      if (typeof (this.totalMap[uniqueId]) != "undefined") {
        this.Map.removeLayer(this.totalMap[uniqueId]);
        delete this.totalMap[uniqueId];
      }
      /**geojson数据 绘制热力图**/
      let geojsonObject = {
        'type': 'FeatureCollection',
        "crs": {
          "type": "name",
          "properties": {
            "name": "urn:ogc:def:crs:OGC:1.3:CRS84"
          }
        },
        'features': []
      };
      for (var i = 0; i < fenbu.length; i++) {
        //console.log($scope.oneData.fenbu[i])
        var feature = {
          'type': 'Feature',
          'geometry': {
            'type': 'Point',
            'coordinates': olProj.transform(fenbu[i], 'EPSG:4326', 'EPSG:3857')
          }
        };
        geojsonObject.features.push(feature);
      }

      let heatmap = new HeatmapLayer({
        source: new VectorSources({
          features: (new GeoJSON()).readFeatures(geojsonObject)
        }),
        blur: parseInt(10, 10),
        radius: parseInt(5, 10)
      });
      this.totalMap[uniqueId] = heatmap;
      this.Map.addLayer(heatmap);
    },
    //地图点击去详情
    mapgodetails(data) {
      if (this.opennew) {
        if (data.path === '/rlc/realtimecameraDetail') {
          this.$router.push({ path: data.path, query: { pageNum: data.pageNum } });
        } else {
          this.$router.push(data.path);
        }
        sessionStorage.setItem('HDD', JSON.stringify(data.data));
      } else {
        this.$emit('openewid', data.path);
      }

    },
    //功能键切换
    openbm(ind) {
      this.b1f = '../../static/images/icon/b1.png';
      this.showList[ind].boo = !this.showList[ind].boo;
      this.showList.forEach((e, index) => {
        if (index != ind) {
          e.boo = false;
        }
        if (ind == 4) {
          this.lon = '';
          this.lat = '';
        }
      })
    },
    //框选网格
    BoxSelection(flag, uniqueId) {
      var select = new Select();
      this.Map.addInteraction(select);
      var selectedFeatures = select.getFeatures();
      var dragBox = new DragBox({
        condition: platformModifierKeyOnly
      });
      this.Map.addInteraction(dragBox);

      var vm = this;
      if (flag) {
        dragBox.on('boxend', function () {
          var rotation = vm.Map.getView().getRotation();
          var oblique = rotation % (Math.PI / 2) !== 0;
          var candidateFeatures = oblique ? [] : selectedFeatures;
          var extent = dragBox.getGeometry().getExtent();
          vm.totalMap[uniqueId].getSource().forEachFeatureIntersectingExtent(extent, function (feature) {
            candidateFeatures.push(feature);
          });
          if (oblique) {
            var anchor = [0, 0];
            var geometry = dragBox.getGeometry().clone();
            geometry.rotate(-rotation, anchor);
            var extent$1 = geometry.getExtent();
            candidateFeatures.forEach(function (feature) {
              var geometry = feature.getGeometry().clone();
              geometry.rotate(-rotation, anchor);
              if (geometry.intersectsExtent(extent$1)) {
                selectedFeatures.push(feature);
              }
            });
          }
        });

        dragBox.on('boxstart', function () {
          selectedFeatures.clear();
        });

        selectedFeatures.on(['add', 'remove'], function () {
          vm.bsl = selectedFeatures.getArray().map(function (feature) {
            return feature.get('customid');
          });
          vm.addContextMenu();
        });

      }
    },
    //添加右键弹窗
    addContextMenu() {
      let vm = this;
      vm.rightMenu = new Cmenu({
        width: 170,
        default_items: true,
        items: [
          {
            text: '选中网格放置1台',
            icon: '../images/anchor.png',
            callback: function (e) {
              var z = {
                name: '网格数据1',
                data: vm.bsl
              }
              vm.$emit("apt", z);
            }
          },
          {
            text: '选中网格放置2台',
            icon: '../images/marker.png',
            callback: function (e) {
              var z = {
                name: '网格数据2',
                data: vm.bsl
              }
              vm.$emit("apt", z);
            }
          },
          {
            text: '选中网格放置3台',
            icon: '../images/marker.png',
            callback: function (e) {
              var z = {
                name: '网格数据1',
                data: vm.bsl
              }
              vm.$emit("apt", z);
            }
          },
          '-' // this is a separator
        ]
      });
      vm.rightMenu.isOpen(false)
      vm.rightMenu.on('beforeopen', function (evt) {
        var feature = vm.Map.forEachFeatureAtPixel(evt.pixel, function (ft, l) {
          return ft;
        });
        if (feature && vm.bsl.length > 0) { // open only on features
          //            vm.rightMenu.enable();
          console.log("里IIIa是");
        } else {
          console.log('进来吗');
          vm.rightMenu.disable();
        }
      });
      this.Map.addControl(vm.rightMenu);
    },
    //二三维切换按钮
    switch3d() {
      this.b1f = '../../static/images/icon/b1.png';
      //        this.ol3d.setEnabled(!this.ol3d.getEnabled());
      this.is3d = !this.is3d;
      if (this.is3d == false) {
        //设置贴地
        this.ol3d.setEnabled(false);
        this.ol3d = {};
      } else {
        //创建cesium
        Cesium.Ion.defaultAccessToken =
          "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiI3NGI1MjIyZS0zYWJlLTQ3NjItOWE4OS01ODNmY2NlM2U2YjYiLCJpZCI6MTc1MDAsInNjb3BlcyI6WyJhc3IiLCJnYyJdLCJpYXQiOjE1NzIzMTc3MzV9.qrvRpIMN_TNPov5uM4q8jOLLGv8EedQ0wXR1uETrL4k";
        //创建cesium
        this.ol3d = new OLCesium({
          map: this.Map,
          time() {
            return Cesium.JulianDate.now();
          }
        });
        const scene = this.ol3d.getCesiumScene();
        scene.terrainProvider = Cesium.createWorldTerrain();
        this.ol3d.setEnabled(true);
      }
      //去除cesium的版本信息
      $('.cesium-credit-lightbox-overlay').prev().hide();
    },
    //测量地图
    cd(ind, type) {
      this.showList.forEach((e, index) => {
        e.boo = false
      });
      this.b1f = '../../static/images/icon/b1.png';
      if (JSON.stringify(this.ol3d) != "{}") {
        this.ol3d.setEnabled(false);
        this.is3d = false;
      }
      var source = new VectorSource();
      var vector = new VectorLayer({
        source: source,
        style: new Style({
          fill: new Fill({
            color: 'rgba(255, 255, 255, 0.2)'
          }),
          stroke: new Stroke({
            color: '#FF8300',
            width: 2
          }),
          image: new CircleStyle({
            radius: 7,
            fill: new Fill({
              color: 'rgba(255,131,0,.2)'
            })
          })
        })
      });
      var sketch;

      var helpTooltipElement;

      var helpTooltip;

      var measureTooltipElement;

      var measureTooltip;

      var _self = this;


      var formatLength = function (line) {
        var length = getLength(line);
        var output;
        if (length > 100) {
          output = (Math.round(length / 1000 * 100) / 100) +
            ' ' + 'km';
        } else {
          output = (Math.round(length * 100) / 100) +
            ' ' + 'm';
        }
        return output;
      };

      var formatArea = function (polygon) {
        var area = getArea(polygon);
        var output;
        if (area > 10000) {
          output = (Math.round(area / 1000000 * 100) / 100) +
            ' ' + 'km<sup>2</sup>';
        } else {
          output = (Math.round(area * 100) / 100) +
            ' ' + 'm<sup>2</sup>';
        }
        return output;
      };


      function createHelpTooltip() {
        if (helpTooltipElement) {
          helpTooltipElement.parentNode.removeChild(helpTooltipElement);
        }
        helpTooltipElement = document.createElement('div');
        helpTooltipElement.className = 'ol-tooltip hidden';
        helpTooltip = new Overlay({
          element: helpTooltipElement,
          offset: [0, -15],
          positioning: 'bottom-center'
        });
        _self.Map.addOverlay(helpTooltip);
      }

      function createMeasureTooltip() {
        if (measureTooltipElement) {
          measureTooltipElement.parentNode.removeChild(measureTooltipElement);
        }
        measureTooltipElement = document.createElement('div');
        measureTooltipElement.className = 'ol-tooltip ol-tooltip-measure';
        measureTooltip = new Overlay({
          element: measureTooltipElement,
          offset: [0, -15],
          positioning: 'bottom-center'
        });
        _self.Map.addOverlay(measureTooltip);
      }

      function addInteraction() {
        _self.drawMesasure = new Draw({
          source: source,
          type: type,
          style: new Style({
            fill: new Fill({
              color: 'rgba(255, 255, 255, 0.2)'
            }),
            stroke: new Stroke({
              color: '#FF8300',
              lineDash: [10, 10],
              width: 2
            }),
            image: new CircleStyle({
              radius: 5,
              stroke: new Stroke({
                color: 'rgba(0, 0, 0, 0.7)'
              }),
              fill: new Fill({
                color: 'rgba(255, 255, 255, 0.2)'
              })
            })
          })
        });
        _self.Map.addInteraction(_self.drawMesasure);
        createMeasureTooltip();
        createHelpTooltip();
        var listener;
        _self.drawMesasure.on('drawstart',
          function (evt) {
            // set sketch
            sketch = evt.feature;
            var tooltipCoord = evt.coordinate;

            listener = sketch.getGeometry().on('change', function (evt) {
              var geom = evt.target;
              var output;
              if (geom instanceof Polygon) {
                output = formatArea(geom);
                tooltipCoord = geom.getInteriorPoint().getCoordinates();
              } else if (geom instanceof LineString) {
                output = formatLength(geom);
                tooltipCoord = geom.getLastCoordinate();
              }
              measureTooltipElement.innerHTML = output;
              // measureTooltipElement.style.color = '#f00000';
              // measureTooltipElement.style.fontSize = '20px';
              measureTooltip.setPosition(tooltipCoord);
            });
          }, this);
        _self.drawMesasure.on('drawend',
          function () {
            measureTooltipElement.className = 'ol-tooltip ol-tooltip-static';
            measureTooltip.setOffset([0, -7]);
            // unset sketch
            sketch = null;
            // unset tooltip so that a new one can be created
            measureTooltipElement = null;
            createMeasureTooltip();
            unByKey(listener);
          }, this);
      }

      if (this.drawMesasure != null) {
        this.Map.getOverlays().clear();
        this.Map.removeLayer(this.totalMap.measure);
        delete this.totalMap.measure;
        this.Map.removeInteraction(this.drawMesasure);
      }

      if (type != 'del') {
        this.totalMap['measure'] = vector;
        this.totalMap['measure'].setZIndex(999);
        this.Map.addLayer(this.totalMap['measure']);
        this.Map.getViewport().addEventListener('mouseout', function () {
          helpTooltipElement.classList.add('hidden');
        });
        addInteraction();
      } else if (type == 'del') {
        this.Map.removeInteraction(this.drawMesasure);
        this.Map.getOverlays().clear();
        if (typeof (this.totalMap.measure) != "undefined") {
          this.Map.removeLayer(this.totalMap.measure);
          delete this.totalMap.measure;
        }
      }

      if (ind == 1) {
        this.b1f = '../../static/images/icon/b2.png';
      }
      if (ind == 2) {
        this.b1f = '../../static/images/icon/b3.png';
      }
      if (ind == 3) {
        console.log('删除');
      }
    },
    //清除图层
    dellayer(id) {
      if (typeof (this.totalMap[id]) != "undefined") {
        this.Map.removeLayer(this.totalMap[id]);
        delete this.totalMap[id];
      }
    },
    //改变样式
    changePointStyle(id, arr, fillColor) {
      if (typeof (this.totalMap[id]) != "undefined") {
        let features = this.totalMap[id].getSource().getFeatures();
        features.forEach(e => {
          arr.forEach(y => {
            if (e.getId() == y) {
              let newPro = e.getProperties();
              newPro.fillColor = fillColor;
              e.setProperties(newPro);
            }
          })
        })
      }
    },
    changeStyle(id, pointId, borderColor, radius, size) {
      if (typeof (this.totalMap[id]) != "undefined") {
        let features = this.totalMap[id].getSource().getFeatures();
        features.forEach(e => {
          let newPro = e.getProperties();
          if (newPro.customid == pointId) {
            newPro.borderColor = borderColor;
            //              newPro.radius = radius;
            newPro.size = size;
            e.setProperties(newPro);
          } else {
            newPro.borderColor = "rgba(255,131,0,0.3)";
            newPro.radius = 6;
            newPro.size = 10;
            e.setProperties(newPro);
          }

          //            arr.forEach(y => {
          //              if (e.getId() == y) {
          //                let newPro = e.getProperties();
          //                newPro.fillColor = fillColor;
          //                e.setProperties(newPro);
          //              }
          //            })
        })
      }
    },
    //切换底图
    switchBmap(g) {
      //首先先清除之前的底图
      this.Map.removeLayer(this.totalMap.bsaeMap);
      delete this.totalMap.bsaeMap;
      //判断文件类型
      if (g.layerType == "xyz") {
        this.drawXYZ('bsaeMap', g.layerUrl);
      }
      if (g.layerType == "wms") {
        this.drawWMS('bsaeMap', g.layerUrl, g.layerName, g.styleId, g.cql);
      }
      if (g.layerType == "wmts") {
        this.drawWMTS('bsaeMap', g.layerUrl, g.layerName, g.matrixSet, g.format, g.style)
      }
      //设置底图层级 避免遮挡后续绘制点位
      this.totalMap['bsaeMap'].setZIndex(1);

      /*this.Map.getView().setMaxZoom(g.maxZoom);
      this.Map.getView().setMinZoom(g.minZoom);*/
    },
    //图层选择项
    dlayer(arr, peg) {
      if (arr.indexOf(peg.name) == -1) {
        if (typeof (this.totalMap[peg.id]) != "undefined") {
          this.Map.removeLayer(this.totalMap[peg.id]);
          delete this.totalMap[peg.id];
        }
      } else {
        if (peg.layerType == "wms") {
          this.drawWMS(peg.id, peg.layerUrl, peg.layerName, peg.styleId, peg.cql);
          this.levelNumber++;
          this.totalMap[peg.id].setZIndex(this.levelNumber);
        } else if (peg.layerType == "xyz") {
          this.drawXYZ(peg.id, peg.layerUrl)
          this.levelNumber++;
          this.totalMap[peg.id].setZIndex(this.levelNumber);
        } else if (peg.layerType == "wmts") {
          this.drawWMTS(peg.id, peg.layerUrl, peg.layerName, peg.matrixSet, peg.format, peg.style);
          this.levelNumber++;
          this.totalMap[peg.id].setZIndex(this.levelNumber);
        } else if (peg.layerType == "shape" || peg.layerType == "custom" || peg.layerType == "excel") {
          let then = this;
          (async function () {
            let res = await http.get(api.NewlayerElementList, {
              dataId: peg.id
            })
            console.log(res, '获取图层');
            then.previewshape(res.data.data, res.data.data[0].layerId);
            then.levelNumber++;
            then.totalMap[peg.id].setZIndex(then.levelNumber);
          })();
        } else {
          let then = this;
          (async function () {
            let res = await http.get(api.geoms + "?id=" + peg.id)
            then.previewshape(res.data.data, res.data.data[0].layerId);
            then.levelNumber++;
            then.totalMap[peg.id].setZIndex(then.levelNumber);
          })();
        }
        //设置图层层级 避免被遮挡

      }
    },
    lbdlayer(arr, peg) {
      console.log(arr, 'arr');
      console.log(peg, 'peg');

      if (arr.indexOf(peg.id) == -1) {
        if (typeof (this.totalMap[peg.layerId]) != undefined) {
          this.Map.removeLayer(this.totalMap[peg.layerId]);
          delete this.totalMap[peg.layerId];
        }
      } else {
        if (peg.layerType == "shape" || peg.layerType == "custom" || peg.layerType == "excel") {
          let then = this;
          (async function () {
            let res = await http.get(api.NewlayerElementList, {
              dataId: peg.id
            })
            console.log(res, '获取图层');
            then.kjlb_previewshape(res.data.data, res.data.data[0].layerId);
            then.levelNumber++;
            then.totalMap[peg.layerId].setZIndex(then.levelNumber);
          })();
        } else if (peg.layerType == "wmts") {
          this.drawWMTS(peg.layerId, peg.layerUrl, peg.layerName, peg.matrixSet, peg.format, peg.styleId)
        } else if (peg.layerType == "wms") {
          this.drawWMS(peg.layerId, peg.layerUrl, peg.layerName, peg.styleId, peg.cql);
          this.levelNumber++;
          this.totalMap[peg.layerId].setZIndex(this.levelNumber);
        } else if (peg.layerType == "xyz") {
          this.drawXYZ(peg.layerId, peg.layerUrl)
          this.levelNumber++;
          this.totalMap[peg.layerId].setZIndex(this.levelNumber);
        }
      }
    },
    //绘制wms类型
    // drawWMS(item, url, name, styleId, cql) {
    //   if (typeof (this.totalMap[item]) == "undefined") {
    //     let params = {
    //       'LAYERS': name,
    //       'STYLES': styleId,
    //       'CQL_FILTER': cql,
    //     };

    //     this.totalMap[item] = new ImageLayer({
    //       source: new ImageWMS({
    //         url: url,
    //         params: params,
    //         serverType: 'geoserver'
    //       })
    //     })
    //     this.Map.addLayer(this.totalMap[item]);
    //   }
    // },

    drawWMS(item, url, name, styleId, cql) {
      if (typeof (this.totalMap[item]) === "undefined") {
        const params = {
          'LAYERS': name,
          'STYLES': styleId,
          'CQL_FILTER': cql,
        };

        const wmsSource = new ImageWMS({
          url: url,
          params: params,
          serverType: 'geoserver',
        });
        this.totalMap[item] = new ImageLayer({
          source: wmsSource,
        });
        this.Map.addLayer(this.totalMap[item]);
        // // 监听图像加载成功和失败事件
        // wmsSource.on('imageloadend', () => {
        //   const extent = wmsSource.image_.extent; // 获取 WMS 图层的范围
        //   const center = getCenter(extent); // 使用 getCenter 函数
        //   console.log(center, 'center');
        //   this.Map.getView().setCenter(center);
        //   // this.Map.getView().fit(extent, { duration: 1000 });
        // });
      }
    },


    //绘制XYZ类型
    drawXYZ(item, url) {
      if (typeof (this.totalMap[item]) == "undefined") {
        this.totalMap[item] = new TileLayer({
          source: new XYZ({
            url: url
          })
        },
        )
        this.Map.addLayer(this.totalMap[item])
      }
    },
    //绘制wmts类型
    // drawWMTS(item, url, layer, matrixSet, format, style) {
    //   console.log(item, url, layer, matrixSet, format, style, 'drawWMTS');

    //   if (typeof (this.totalMap[item]) == "undefined") {
    //     var projection = olProj.get('EPSG:4326');
    //     var projectionExtent = projection.getExtent();
    //     var size = getWidth(projectionExtent) / 256;
    //     var resolutions = new Array(14);
    //     var matrixIds = new Array(14);
    //     for (var z = 0; z < 14; ++z) {
    //       resolutions[z] = size / Math.pow(2, z);
    //       matrixIds[z] = z;
    //     }
    //     this.totalMap[item] = new TileLayer({
    //       source: new WMTS({
    //         url: url,
    //         layer: layer,
    //         matrixSet: matrixSet,
    //         format: format,
    //         projection: projection,
    //         // tileGrid: new WMTSTileGrid({
    //         //   origin: getTopLeft(projectionExtent),
    //         //   resolutions: resolutions,
    //         //   matrixIds: matrixIds
    //         // }),
    //         tileGrid: new ol.tilegrid.WMTS({
    //           extent: ol.proj.transformExtent([-180, -90, 180, 90], 'EPSG:4326', 'EPSG:3857'),
    //           resolutions: resolutions,
    //             matrixIds: matrixIds
    //         }),
    //         style: style,
    //       })
    //     });
    //     this.Map.addLayer(this.totalMap[item])
    //   }
    // },


    drawWMTS(item, url, layer, matrixSet, format, style) {
      if (typeof this.totalMap[item] == "undefined") {
        var projection = olProj.get("EPSG:4326");
        var projectionExtent = projection.getExtent();
        var size = getWidth(projectionExtent) / 256;
        var resolutions = new Array(14);
        var matrixIds = new Array(14);
        for (var z = 0; z < 14; ++z) {
          resolutions[z] = size / Math.pow(2, z);
          matrixIds[z] = z;
        }
        this.totalMap[item] = new TileLayer({
          source: new WMTS({
            url: url,
            layer: layer,
            matrixSet: matrixSet,
            format: format,
            projection: projection,
            tileGrid: new WMTSTileGrid({
              origin: getTopLeft(projectionExtent),
              resolutions: resolutions,
              matrixIds: matrixIds
            }),
            style: style
          })
        });
        this.Map.addLayer(this.totalMap[item]);
      }
    },


    // drawWMTS(item, url, layer, matrixSet, format, style) {
    //   console.log(item, url, layer, matrixSet, format, style, 'drawWMTS');

    //   if (typeof this.totalMap[item] === "undefined") {
    //     const projection = olProj.get('EPSG:4326');
    //     const projectionExtent = projection.getExtent();
    //     const size = getWidth(projectionExtent) / 256;
    //     const resolutions = Array.from({ length: 14 }, (_, z) => size / Math.pow(2, z));
    //     const matrixIds = Array.from({ length: 14 }, (_, z) => z);

    //     this.totalMap[item] = new TileLayer({
    //       source: new WMTS({
    //         url: url,
    //         layer: layer,
    //         matrixSet: matrixSet,
    //         format: format,
    //         projection: projection,
    //         tileGrid: new WMTSTileGrid({
    //           extent: olProj.transformExtent([-180, -90, 180, 90], 'EPSG:4326', 'EPSG:3857'),
    //           resolutions: resolutions,
    //           matrixIds: matrixIds
    //         }),
    //         style: style,
    //       })
    //     });
    //     console.log(this.totalMap[item], 'console.log(this.totalMap[item]);');
    //     this.Map.addLayer(this.totalMap[item]);
    //   }
    // },




    //绘制geojson类型
    previewshape(data, id) {
      var vm = this;
      //判断是否已经存在相同id的图层 如果有删掉，再重新绘制
      if (typeof (this.totalMap[id]) != "undefined") {
        this.Map.removeLayer(this.totalMap[id]);
        delete this.totalMap[id];
      }
      let styleFunction = function () {
        return function (feature, resolution) {
          //点
          if (feature.getGeometry().getType() == 'Point') {
            if (feature.get('fillColor').indexOf('#') != -1) {
              var point = new Style({
                image: new CircleStyle({
                  radius: feature.get("radius"),
                  fill: new Fill({
                    color: feature.get("fillColor")
                  }),
                  stroke: new Stroke({
                    color: feature.get("borderColor"),
                    width: feature.get("size")
                  })
                }),
                text: new Text({
                  font: '12px Calibri,sans-serif',
                  text: feature.get('text'),
                  fill: new Fill({
                    color: feature.get('fillColor')
                  }),
                  offsetY: 15,
                  stroke: new Stroke({
                    color: 'white',
                    width: 1
                  }),
                })
              })
            } else {
              var point = new Style({
                image: vm.addImage(feature, resolution),
                text: new Text({
                  font: '12px Calibri,sans-serif',
                  text: feature.get('text'),
                  fill: new Fill({
                    color: feature.get('fillColor')
                  }),
                  offsetY: 15,
                  stroke: new Stroke({
                    color: 'white',
                    width: 1
                  }),
                })
              })
            }
            return [point]
          }
          if (feature.getGeometry().getType() == 'MultiPoint') {
            var MultiPoint = new Style({
              image: new CircleStyle({
                radius: 5,
                fill: new Fill({
                  color: feature.get("fillColor")
                }),
                stroke: new Stroke({
                  color: feature.get("borderColor"),
                  width: feature.get("size")
                })
              }),
              text: new Text({
                font: '12px Calibri,sans-serif',
                text: feature.get('text'),
                fill: new Fill({
                  color: feature.get('fillColor')
                }),
                offsetY: 15,
                stroke: new Stroke({
                  color: 'white',
                  width: 1
                }),
              })
            })
            return [MultiPoint]
          }
          //面
          if (feature.getGeometry().getType() == 'MultiPolygon') {
            var MultiPolygon = new Style({
              stroke: new Stroke({
                color: feature.get('lineColor') || 'white',
                width: feature.get("lineWidth") || 3
              }),
              fill: new Fill({
                color: feature.get("fillColor")
              }),
              text: new Text({
                font: '16px Calibri,sans-serif',
                text: feature.get('text'),
                fill: new Fill({
                  color: feature.get('textColor')
                }),
                stroke: new Stroke({
                  color: feature.get('textColor'),
                  width: 1
                })
              })
            })
            return [MultiPolygon]
          }
          if (feature.getGeometry().getType() == 'Polygon') {
            var Polygon = new Style({
              stroke: new Stroke({
                color: feature.get('lineColor') || 'white',
                width: feature.get("lineWidth") || 3
              }),
              fill: new Fill({
                color: feature.get("fillColor")
              }),
              text: new Text({
                font: '12px Calibri,sans-serif',
                text: feature.get('text'),
                fill: new Fill({
                  color: feature.get('borderColor')
                }),
                stroke: new Stroke({
                  color: 'white',
                  width: 3
                }),
              })
            })
            return [Polygon]
          }
          //线
          if (feature.getGeometry().getType() == 'LineString') {
            var LineString = new Style({
              stroke: new Stroke({
                color: feature.get('borderColor'),
                width: feature.get("size") + 3
              }),
              text: new Text({
                font: '12px Calibri,sans-serif',
                text: feature.get('text'),
                fill: new Fill({
                  color: 'white'
                }),
                stroke: new Stroke({
                  color: 'block',
                  width: 2
                }),
              })
            })
            return [LineString]
          }
          //多线
          if (feature.getGeometry().getType() == 'MultiLineString') {
            var MultiLineString = new Style({
              stroke: new Stroke({
                color: feature.get('borderColor'),
                width: feature.get("size") + 3
              }),
              text: new Text({
                font: '12px Calibri,sans-serif',
                text: feature.get('text'),
                fill: new Fill({
                  color: 'white'
                }),
                stroke: new Stroke({
                  color: 'block',
                  width: 2
                }),
              })
            })
            return [MultiLineString]
          }
        }
      };
      let geojsonObject = {
        'type': 'FeatureCollection',
        'crs': {
          'type': 'name',
          'properties': {
            'name': 'EPSG:4326'
          }
        },
        'features': []
      };
      this.vectorSource = new VectorSource({
        features: (new GeoJSON(
          {
            defaultDataProjection: 'EPSG:4326',
            featureProjection: 'EPSG:3857'
          }
        )).readFeatures(geojsonObject)
      });
      this.totalMap[id] = new VectorLayer({
        source: this.vectorSource,
        style: styleFunction()
      });

      let sources = this.totalMap[id].getSource();
      data.forEach((e => {
        sources.addFeatures(
          (new GeoJSON({
            defaultDataProjection: 'EPSG:4326',
            featureProjection: 'EPSG:3857'
          })).readFeatures({
            "id": e.id,
            "properties": {
              "name": e.name,
              "borderColor": e.borderColor,
              "fillColor": e.fillColor,
              "iconSrc": e.iconSrc,
              "size": e.size,
              "radius": 6,
              "isdetails": e.isdetails,
              "isdetailsTetx": e.isdetailsTetx,
              "isdetailsLink": e.isdetailsLink,
              "opennew": e.opennew,
              "text": e.name,
              "data": e.data,
              "textColor": e.textColor,
              'customid': e.id
            },
            'type': 'Feature',
            'geometry': e.geojson
          }))
      }));
      this.totalMap[id].set("altitudeMode", "clampToGround");
      this.Map.addLayer(this.totalMap[id]);
      //绘制点线的时候  给  图层id 加上 @Point||@LineString  然后给点线的层级设高 高于面的
      // 避免显示地图弹窗的时候 面遮住点线 点击不到 点线的feature
      var drawType = id.split("_");
      if (drawType[drawType.length - 1] == 'Point') {
        this.totalMap[id].setZIndex(299 + this.levelNumber);
      }
      if (drawType[drawType.length - 1] == 'LineString') {
        this.totalMap[id].setZIndex(199 + this.levelNumber);
      }
      let centerid = data[0].id,
        thisfeature = this.vectorSource.getFeatureById(centerid),
        center = thisfeature.getGeometry().getFirstCoordinate();
      this.Map.getView().setCenter(center);
    },
    //绘制勘界立标geojson类型
    kjlb_previewshape(data, id) {
      // const popup = document.getElementById('newpopup');
      const popupContent = document.getElementById('newpopup-content');
      const popupCloser = document.getElementById('newpopup-closer');
      const popup = new Overlay({
        element: document.getElementById('popup'),
        positioning: 'bottom-center', // 设置弹窗位置
        stopEvent: true, // 停止事件传播
        autoPan: true, // 自动平移
        autoPanAnimation: {
          duration: 250
        }
      });
      this.Map.addOverlay(popup);
      // 关闭弹窗的逻辑
      popupCloser.onclick = function () {
        popup.getElement().style.display = 'none';
        return false; // 防止链接的默认行为
      };
      var vm = this;
      //判断是否已经存在相同id的图层 如果有删掉，再重新绘制
      if (typeof (this.totalMap[id]) != "undefined") {
        this.Map.removeLayer(this.totalMap[id]);
        delete this.totalMap[id];
      }
      let styleFunction = function () {
        return function (feature, resolution) {
          //点
          if (feature.getGeometry().getType() == 'Point') {
            // if (feature.get('fillColor').indexOf('#') != -1) {
            var point = new Style({
              image: new CircleStyle({
                radius: 5,
                fill: new Fill({
                  color: feature.get('pointColor') || 'white',
                }),
                // stroke: new Stroke({
                //   color: '#ffcc33',
                //   width: 2,
                // })
              })
            })

            // image: new CircleStyle({
            //   radius: feature.get("radius"),
            //   fill: new Fill({
            //     color: feature.get("fillColor")
            //   }),
            //   stroke: new Stroke({
            //     color: feature.get("borderColor"),
            //     width: feature.get("size")
            //   })
            // }),
            // text: new Text({
            //   font: '12px Calibri,sans-serif',
            //   text: feature.get('text'),
            //   fill: new Fill({
            //     color: feature.get('fillColor')
            //   }),
            //   offsetY: 15,
            //   stroke: new Stroke({
            //     color: feature.get('pointColor'),
            //     width: 1
            //   }),
            // })

            // } else {
            //   var point = new Style({
            //     image: vm.addImage(feature, resolution),
            //     text: new Text({
            //       font: '12px Calibri,sans-serif',
            //       text: feature.get('text'),
            //       fill: new Fill({
            //         color: feature.get('fillColor')
            //       }),
            //       offsetY: 15,
            //       stroke: new Stroke({
            //         color: 'white',
            //         width: 1
            //       }),
            //     })
            //   })
            // }
            return [point]
          }
          if (feature.getGeometry().getType() == 'MultiPoint') {
            var MultiPoint = new Style({
              image: new CircleStyle({
                radius: 5,
                fill: new Fill({
                  color: feature.get("fillColor") || 'red'
                }),
                stroke: new Stroke({
                  color: feature.get("borderColor"),
                  width: feature.get("size")
                })
              }),
              text: new Text({
                font: '12px Calibri,sans-serif',
                text: feature.get('text'),
                fill: new Fill({
                  color: feature.get('fillColor') || 'red'
                }),
                offsetY: 15,
                stroke: new Stroke({
                  color: 'white',
                  width: 1
                }),
              })
            })
            return [MultiPoint]
          }
          //面
          if (feature.getGeometry().getType() == 'MultiPolygon') {
            var MultiPolygon = new Style({
              stroke: new Stroke({
                color: feature.get('borderColor') || 'red',
                width: feature.get("lineWidth") || 1
              }),
              fill: new Fill({
                color: feature.get("fillColor") || 'rgba(225, 230, 234, 0.5)'
              }),
              text: new Text({
                font: '16px Calibri,sans-serif',
                text: feature.get('text'),
                fill: new Fill({
                  color: feature.get('textColor')
                }),
                stroke: new Stroke({
                  color: feature.get('textColor'),
                  width: 1
                })
              })
            })
            return [MultiPolygon]
          }
          if (feature.getGeometry().getType() == 'Polygon') {
            var Polygon = new Style({
              stroke: new Stroke({
                color: feature.get('borderColor') || 'red',
                width: feature.get("lineWidth") || 1
              }),
              fill: new Fill({
                color: feature.get("fillColor") || 'rgba(225, 230, 234, 0.5)'
              }),
              text: new Text({
                font: '12px Calibri,sans-serif',
                text: feature.get('text'),
                fill: new Fill({
                  color: feature.get('borderColor')
                }),
                stroke: new Stroke({
                  color: 'white',
                  width: 3
                }),
              })
            })
            return [Polygon]
          }
          //线
          if (feature.getGeometry().getType() == 'LineString') {
            var LineString = new Style({
              stroke: new Stroke({
                color: feature.get('borderColor') || 'red',
                width: feature.get("lineWidth") || 1
              }),
              text: new Text({
                font: '12px Calibri,sans-serif',
                text: feature.get('text'),
                fill: new Fill({
                  color: 'white'
                }),
                stroke: new Stroke({
                  color: 'block',
                  width: 2
                }),
              })
            })
            return [LineString]
          }
          //多线
          if (feature.getGeometry().getType() == 'MultiLineString') {
            var MultiLineString = new Style({
              stroke: new Stroke({
                color: feature.get('borderColor') || 'white',
                width: feature.get("lineWidth") || 3
              }),
              text: new Text({
                font: '12px Calibri,sans-serif',
                text: feature.get('text'),
                fill: new Fill({
                  color: 'white'
                }),
                stroke: new Stroke({
                  color: 'block',
                  width: 2
                }),
              })
            })
            return [MultiLineString]
          }
        }
      };
      let geojsonObject = {
        'type': 'FeatureCollection',
        'crs': {
          'type': 'name',
          'properties': {
            'name': 'EPSG:4326'
          }
        },
        'features': []
      };
      this.vectorSource = new VectorSource({
        features: (new GeoJSON(
          {
            defaultDataProjection: 'EPSG:4326',
            featureProjection: 'EPSG:3857'
          }
        )).readFeatures(geojsonObject)
      });
      this.totalMap[id] = new VectorLayer({
        source: this.vectorSource,
        style: styleFunction()
      });
      // 为特征添加点击事件
      const mapLB = this.Map;
      const selectInteraction = new Select({
        source: this.vectorSource,
        style: null, // 可以选择不改变样式，或者定义其他样式
      });
      selectInteraction.on('select', function (event) {
        event.selected.forEach((feature) => {
          const properties = feature.getProperties();
          console.log(properties, 'properties');
          const pixel = event.mapBrowserEvent.pixel;
          const coordinate = mapLB.getCoordinateFromPixel(pixel);
          const offsetX = -20; // 根据需要调整 X 偏移量
          const offsetY = -20; // 根据需要调整 Y 偏移量
          const adjustedCoordinate = [coordinate[0] + offsetX, coordinate[1] + offsetY];
          popup.setPosition(adjustedCoordinate);
          // popup.setPosition(coordinate);
          popupContent.innerHTML = '';
          // 显示弹窗并设置内容
          this.kjlbArr = properties.data;
          if (this.kjlbArr.length > 0) {
            this.kjlbArr.forEach((e) => {
              popupContent.innerHTML += `
            <div class="popup-header" style="font-size: .16rem; font-weight: bold;">${e.label}: ${e.value}</div>
        `;
            });
          } else {
            popupContent.innerHTML += `
            <div class="popup-header" style="font-size: .16rem; font-weight: bold;">暂无信息...</div>
        `;
          }
          popup.getElement().style.display = 'block';
        });
      });

      let sources = this.totalMap[id].getSource();
      data.forEach((e => {
        console.log(e, 'eeeee');

        sources.addFeatures(
          (new GeoJSON({
            defaultDataProjection: 'EPSG:4326',
            featureProjection: 'EPSG:3857'
          })).readFeatures({
            "id": e.id,
            "properties": {
              "name": e.name,
              "borderColor": e.lineColor,
              "fillColor": e.fillColor,
              "lineWidth": e.lineWidth,
              "iconSrc": e.iconSrc,
              "size": e.size,
              "radius": 6,
              "isdetails": e.isdetails,
              "isdetailsTetx": e.isdetailsTetx,
              "isdetailsLink": e.isdetailsLink,
              "opennew": e.opennew,
              "text": e.name,
              "data": e.itemData,
              "textColor": e.textColor,
              'customid': e.id,
              'pointColor': e.pointColor,
              // 'pointHigh': e.pointHigh,
              // 'pointWidth': e.pointWidth,
            },
            'type': 'Feature',
            'geometry': e.geojson
          }))
      }));
      this.totalMap[id].set("altitudeMode", "clampToGround");
      this.Map.addLayer(this.totalMap[id]);
      this.Map.addInteraction(selectInteraction);
      //绘制点线的时候  给  图层id 加上 @Point||@LineString  然后给点线的层级设高 高于面的
      // 避免显示地图弹窗的时候 面遮住点线 点击不到 点线的feature
      var drawType = id.split("_");
      if (drawType[drawType.length - 1] == 'Point') {
        this.totalMap[id].setZIndex(299 + this.levelNumber);
      }
      if (drawType[drawType.length - 1] == 'LineString') {
        this.totalMap[id].setZIndex(199 + this.levelNumber);
      }
      let centerid = data[0].id,
        thisfeature = this.vectorSource.getFeatureById(centerid),
        center = thisfeature.getGeometry().getFirstCoordinate();
      this.Map.getView().setCenter(center);
    },
    //点类型绘制图标 需要定位图标位置
    //地图图标位置处理函数
    addImage(feature, resolution) {
      let src = feature.get('iconSrc');
      let anchor = [0, 1];
      //根据图标文件名 设置定位点  地图上放置的图标更改文件名即可保持一致
      if (src != '') {
        if (src.indexOf('anchor_bottom_center') != -1) {
          anchor = [0.5, 1];
        } else if (src.indexOf('anchor_bottom_left') != -1) {
          anchor = [0, 1];
        } else if (src.indexOf('anchor_bottom_right') != -1) {
          anchor = [1, 1];
        } else if (src.indexOf('anchor_center_center') != -1) {
          anchor = [0.5, 0.5];
        } else if (src.indexOf('anchor_top_center') != -1) {
          anchor = [0.5, 0];
        } else if (src.indexOf('anchor_top_left') != -1) {
          anchor = [0, 0];
        } else if (src.indexOf('anchor_top_right') != -1) {
          anchor = [1, 0];
        }
        return new Icon({
          src: feature.get('iconSrc'),
          anchor: anchor,
        });
      }
    },
    //定位
    setLocation(x, y) {
      if (x == '' || y == '') {
        this.warn('请输入经纬度信息')
      } else {
        this.dwindex++;
        let jw = [parseFloat(x), parseFloat(y)];
        this.Map.getView().setCenter(olProj.transform(jw, 'EPSG:4326', 'EPSG:3857'));
        var arr = [{
          id: "312ty834y7823y872389eh23894y23894yu2389",
          name: "",
          borderColor: "",
          fillColor: "",
          iconSrc: "../../static/images/dingwei_anchor_bottom_center.png",
          data: {
            mtl: [],
            id: "312ty834y7823y872389eh23894y23894yu2389",
            size: 1,
            isdetails: false,
            isdetailsTetx: "",
            opennew: false,
            isdetailsLink: "",
            mediaList: []
          },
          geojson: { coordinates: jw, type: "Point" }
        }];
        this.previewshape(arr, "label" + this.dwindex);
      }

    },
    //删除定位
    delLocation() {
      for (let k in this.totalMap) {
        if (k.indexOf('label') != -1) {
          this.dellayer(k)
        }
      }
    },
    //关闭弹窗
    closer() {
      var closer = document.getElementById('popup-closer');
      this.puplay.setPosition(undefined);
      closer.blur();
      return false
    },
    //判断云服务or本地服务
    iscloud(p) {
      if (p.length != 0) {
        if (p[0].split(":")[0] == 'http' || p[0].split(":")[0] == 'https') {
          return p[0]
        } else {
          return '/iapi' + p[0]
        }
      }
      if (p.length == 0) {
        return '../../static/images/np.jpg'
      }
    },
    //判断文件类型
    isMp4(m) {
      let iv = m.split('.');
      if (iv[iv.length - 1].toLowerCase() == 'mp4') {
        return '视频'
      } else {
        return '照片'
      }
    },
    //传递图片
    fimg(data) {
      if (data.length != 0) {
        let z = {
          name: "图集",
          data: data
        }
        this.$emit('apt', z)
      }

    },
    //警示提示
    warn(text) {
      this.$message({
        message: text,
        type: "warning"
      });
    },
    //监测页面大小
  }
};
</script>

<style scoped>
@import "../../static/css/mapModule.css";

#mouse-position {
  position: absolute;
  bottom: .2rem;
  left: 2rem;
  z-index: 100;
}
</style>
<style>
/*.ol-overlay-container span {*/
/*  display: block;*/
/*  width: 50px;*/
/*  height: 50px;*/
/*  border-radius: 50%;*/
/*  background: url("../../static/images/icon/gif.gif") no-repeat;*/
/*  background-size: 50px 50px;*/
/*}*/
.newfx {
  padding: 20px 20px 0 20px;
  position: absolute;
  top: 6px;
  left: 0;
  border-radius: 4px;
  box-shadow: 0 3px 24px 0 rgba(0, 0, 0, 0.12);
  background-color: #fff;
  overflow: hidden;
  height: 700px;
  overflow: auto;
}

.fx .el-checkbox:last-of-type {
  margin-right: .3rem;
}

.cesium-widget-credits {
  display: none
}

.cesium-viewer .cesium-widget-credits {
  display: none
}

.custom-mouse-position {
  color: white;
  z-index: 999;
}

.ol-tooltip {
  position: relative;
  background: rgba(0, 0, 0, 0.5);
  border-radius: 4px;
  color: white;
  padding: 4px 8px;
  opacity: 0.7;
  white-space: nowrap;
  font-size: 12px;
}

.ol-tooltip-measure {
  opacity: 1;
  font-weight: bold;
}

.ol-tooltip-static {
  background-color: #ffcc33;
  color: black;
  border: 1px solid white;
}

.ol-tooltip-measure:before,
.ol-tooltip-static:before {
  border-top: 6px solid rgba(0, 0, 0, 0.5);
  border-right: 6px solid transparent;
  border-left: 6px solid transparent;
  content: "";
  position: absolute;
  bottom: -6px;
  margin-left: -7px;
  left: 50%;
}

.ol-tooltip-static:before {
  border-top-color: #ffcc33;
}



.new-popup {
  position: absolute;
  background: white;
  border: 1px solid black;
  padding: 15px;
  bottom: 12px;
  left: -60px;
  z-index: 1000;
}

.content-box {
  min-width: 2rem;
}

.popup-header {
  width: 100%;
  height: 100%;
}

/* .ol-popup-closer {
  position: absolute;
  top: 2px;
  right: 2px;
  text-decoration: none;
  font-weight: bold;
  color: black;
} */
</style>
